<template>
  <el-dialog
    v-el-drag-dialog="{minWidth: 750, updataFull, updataDialogWidth}"
    :fullscreen="isfullscreen"
    :width="setDialogWidth('90%')"
    :visible="visible"
    :title="$t('INTELLIGENCE_RECOVERY')"
    :append-to-body="true"
    @open="open"
    @close="close"
  >
    <template v-slot:title>
      <div class="flex align-start" style="width: calc(100% - 80px)">
        <span class="el-dialog__title mr-30">
          {{ $t('INTELLIGENCE_RECOVERY') }}
        </span>
        <!-- 步骤条 -->
        <steps-bar :steps="steps" :current="step" />
      </div>
    </template>
    <!-- 业务基本信息显示 -->
    <biz-info :form-data="rowData" />
    <!-- 图形化 -->
    <div class="font-weight-bold pl-20">{{ $t('INTERMEDIATE_NODE') }}</div>
    <el-divider class="m-0 mt-10 mb-10" />
    <otdr-test-btn
      v-if="step > 1"
      ref="otdrTestBtn"
      class="w-100 mb-10"
      :form-data="formData"
      @taskChange="taskChange"
    />
    <biz-graphical
      ref="bizGraphical"
      :biz-channel-list="graphicalSegmentList"
      :cable-data="graphicalCableData"
      operate-type="open"
    />
    <!-- 第一步：展示已选备用通道和重新推荐列表 -->
    <div v-show="step === 1">
      <el-tabs v-if="showTabs" v-model="activeName" type="card">
        <el-tab-pane :label="$t('SELECT_CONFIGURED_CHANNEL')" name="configed">
          <div v-if="backChannelList.length === 0" class="no-data">
            {{ $t('NO_CONFIGED_BACKUP') }}
          </div>
          <div class="tab-overflow">
            <div v-for="(item, index) in backChannelList" :key="index">
              <channel-list
                class="mb-10"
                type="configed"
                :row-data="item"
                operate-type="restore"
                :show-cutover-list="false"
                :form-data="formData"
                @configedSelected="configedSelected"
              />
            </div>
          </div>
        </el-tab-pane>
        <el-tab-pane :label="$t('RECOMMENDER')" name="new">
          <recommend ref="newRecommend" :form-data="formData" operate-type="restore" />
        </el-tab-pane>
      </el-tabs>
    </div>
    <!-- 第二步：展示已选信息 和 OTDR测试 -->
    <step-two
      v-if="step === 2"
      ref="stepTwo"
      :form-data="formData"
      @reLinkRecommend="reLinkRecommend"
    />
    <template v-slot:footer>
      <el-button @click="close">{{ $t('CANCEL') }}</el-button>
      <el-button v-if="step === 2" @click="previous">{{ $t('PREVIOUS') }}</el-button>
      <el-button
        v-if="step === 1"
        type="primary"
        :disabled="step === 1 && !formData.routeData"
        @click="next"
      >{{ $t('NEXT') }}</el-button>
      <el-button v-if="step === 2" type="primary" @click="$debounce(save)">{{
        $t('SAVE')
      }}</el-button>
    </template>
  </el-dialog>
</template>

<script>
  import { mapGetters } from 'vuex'
  import bizOpenApi from '@/api/oen/BizOpenApi'
  import backChannelApi from '@/api/oen/BackChannelApi'
  import { deepClone, checkAfs } from '@/utils/common'
  import Recommend from './components/Recommend'
  import StepTwo from './components/open/StepThree'
  import ChannelList from '@/components/ChannelList'
  import BizInfo from './components/BizInfo'
  import StepsBar from '@/components/StepsBar'
  import BizGraphical from '@/components/BizGraphical'
  import OtdrTestBtn from '@/components/OtdrTestBtn'

  export default {
    components: { Recommend, StepTwo, BizInfo, ChannelList, StepsBar, BizGraphical, OtdrTestBtn },
    props: {
      visible: {
        type: Boolean,
        default: false
      },
      rowData: {
        type: Object,
        default: () => {}
      }
    },
    data() {
      return {
        steps: ['SELECT_RECOVERY_CHANNEL', 'PRE_RECOVERY_DETECTION', 'COMPLETE'],
        showTabs: false,
        step: 1,
        activeName: 'configed',
        isRecommended: false,
        formData: {
          selectedType: '',
          segmentList: [],
          routeData: null,
          channelData: []
        },
        backChannelList: [],
        bizChannelList: [],
        graphicalSegmentList: [],
        graphicalCableData: {},
        isOtdrTesting: false
      }
    },
    computed: {
      ...mapGetters(['baseRegionList'])
    },
    watch: {
      activeName(newVal) {
        // 只有第一次切换推荐tab才请求数据
        if (newVal === 'new' && !this.isRecommended) {
          this.$nextTick(() => {
            this.$refs.newRecommend && this.$refs.newRecommend.getRouteList('restore')
            this.isRecommended = true
          })
        }
        this.resetSelected()
      },
      'formData.channelData': {
        handler() {
          this.changeGraphical()
        },
        immediate: true,
        deep: true
      }
    },
    methods: {
      open() {
        this.showTabs = true
        this.step = 1
        this.activeName = 'configed'
        this.isRecommended = false
        this.backChannelList = []
        const formData = {
          bizId: this.rowData.bizId,
          bizName: this.rowData.bizName,
          aStationId: this.rowData.startStationId,
          aNodeId: this.rowData.startNodeId,
          zStationId: this.rowData.endStationId,
          zNodeId: this.rowData.endNodeId,
          aNodeData: this.rowData.startNode,
          zNodeData: this.rowData.endNode,
          aPortData: {},
          zPortData: {},
          aPortData2: {},
          zPortData2: {}
        }
        const firstData = this.rowData.bizChannelList[0]
        formData.aPortData.portId = firstData.startPortId
        formData.aPortData.regionName = this.getRegionName(formData.aStationId)
        formData.zPortData.portId = firstData.endPortId
        formData.zPortData.regionName = this.getRegionName(formData.zStationId)
        if (this.rowData.bizChannelList.length === 2) {
          const secondData = this.rowData.bizChannelList[1]
          formData.aPortData2.portId = secondData.startPortId
          formData.zPortData2.portId = secondData.endPortId
        }
        formData.channelData = this.rowData.channelList
        formData.functionName = 'manager' // 操作日志需要传此类型，判断是topo还是业务管理里执行的恢复
        formData.actionName = 'restore' // 操作日志需要传此类型，判断是开通或者恢复前otdr测试
        this.formData = { ...this.$options.data().formData, ...formData }
        this.getBackDetail()
      },
      // 获取备用详情
      getBackDetail() {
        backChannelApi
          .detail({
            bizId: this.rowData.bizId
          })
          .then(res => {
            if (!res) return
            this.backChannelList = this.formatData(res.backChannelList)
            this.bizChannelList = res.mainChannelList.map(i => i.channelList)
          })
      },
      // 拼装组合通道展示数据
      formatData(data) {
        // 拼接组合数据：同链路数据拼接到一条里面
        const newList = []
        data.forEach(i => {
          // 设置链路唯一linkId 使用通道id拼接保证一定是唯一的
          i.linkId = i.segmentList.map(j => j.id).join()
          const theIndex = newList.findIndex(j => j.linkId === i.linkId)
          const item = deepClone(i)
          const channelItem = {
            segmentListIds: i.linkId,
            loss: i.loss,
            backId: i.backId,
            exclusive: i.exclusive ? 'EXCLUSIVE' : 'SHARE',
            segmentList: i.channelList
          }
          if (theIndex !== -1) {
            newList[theIndex].channelList.push(channelItem)
          } else {
            item.channelList = [channelItem]
            newList.push(item)
          }
        })
        // 同链路通道拼接完成，设置表单显示信息
        newList.forEach(z => {
          z.channelList.forEach(i => {
            i.segmentList.forEach((j, index) => {
              j.startPort.bizName = this.$utils.handleServiceI18n(j.startPort.bizName)
              j.endPort.bizName = this.$utils.handleServiceI18n(j.endPort.bizName)
              i['segmentList' + index] = j
            })
          })
        })

        return newList
      },
      changeGraphical() {
        console.log('this.formData', this.formData)
        if (!this.formData.routeData) {
          this.graphicalSegmentList = []
          this.graphicalCableData = {}
        } else {
          const routeSegmentList = this.formData.routeData.segmentList
          const channelData = this.formData.channelData
          routeSegmentList.forEach((i, index) => {
            channelData[0].segmentList[index] = {
              ...channelData[0].segmentList[index],
              startNode: routeSegmentList[index].startNode,
              endNode: routeSegmentList[index].endNode
            }
            if (channelData.length === 2) {
              channelData[1].segmentList[index] = {
                ...channelData[1].segmentList[index],
                startNode: routeSegmentList[index].startNode,
                endNode: routeSegmentList[index].endNode
              }
            }
            if (i.cableId) {
              this.graphicalCableData[i.cableId] = i.cable
            }
          })
          this.graphicalSegmentList = channelData
        }
        this.$nextTick(() => {
          this.$refs.bizGraphical && this.$refs.bizGraphical.formatData()
        })
      },
      // 下一步
      async next() {
        if (!this.formData.routeData) {
          this.$message.error(this.$t('SELECT_RECOVER_CHANNELR'))
          return
        }
        if (this.formData.channelData.some(i => i.isReach === false)) {
          this.$message.error(this.$t('CHANNEL_UNREACHABLE'))
          return
        }
        // 双芯判断
        if (this.rowData.bizChannelList.length === 2) {
          const channelData = this.formData.channelData
          // 1.必须两条通道；2.同一链路；3.不同端口
          if (
            channelData.length !== 2 ||
            channelData[0].segmentListIds !== channelData[1].segmentListIds ||
            channelData[0].segmentList0.startPortId === channelData[1].segmentList0.startPortId
          ) {
            this.$message.error(this.$t('DOUBLE_NEED_TWO'))
            return
          }
        } else {
          // 单芯只能选一条通道
          if (this.formData.channelData.length > 1) {
            this.$message.error(this.$t('SINGLE_CORE_PORT'))
            return
          }
        }
        // 判断选中的通道AFS设备是否可用
        const checkeAfs = await checkAfs(this.formData, 'INTELLIGENCE_RECOVERY')
        if (!checkeAfs) return
        this.step = 2
      },
      async save() {
        // 数据拼接
        console.log('this.formData', this.formData)
        // 判断otdr测试是否正在执行中
        if (this.isOtdrTesting) {
          this.$message.error(this.$t('CONFIRM_RESTORE'))
          return
        }
        // 判断选中的通道AFS设备是否可用
        const checkeAfs = await checkAfs(this.formData, 'INTELLIGENCE_RECOVERY')
        if (!checkeAfs) return
        const formData = deepClone(this.formData)
        const cutoverList = formData.channelData.map(i => {
          const cutoverData = i.cutoverList.map(j => {
            return {
              ...j,
              portName: j.port.bizName,
              connPortName: j.connPort.bizName
            }
          })
          return {
            backId: this.formData.selectedType === 'configed' ? i.backId : '',
            segmentChannelList: i.segmentList,
            cutoverList: cutoverData
          }
        })
        const queryData = {
          startStationName: this.rowData.startStationName, // 操作日志需要，后端不需要此参数
          bizName: this.rowData.bizName, // 操作日志需要，后端不需要此参数
          functionName: this.rowData.functionName, // 操作日志需要，后端不需要此参数
          bizId: this.rowData.bizId,
          cutoverList: cutoverList
        }
        // console.log('queryData', queryData)
        bizOpenApi.restore(queryData).then(res => {
          this.$message.success(this.$t('REQUEST_SUCCESS'))
          this.close(true)
        })
      },
      // 上一步
      previous() {
        if (
          this.$refs.otdrTestBtn.completed ||
          this.$refs.otdrTestBtn.failed ||
          this.isOtdrTesting
        ) {
          this.$confirm(this.$t('CONFIRM_PREVIOUS_STEP'), {
            type: 'warning',
            confirmButtonText: this.$t('OK_YES'),
            cancelButtonText: this.$t('OK_NO')
          })
            .then(() => {
              this.step--
            })
            .catch(() => {})
        } else {
          this.step--
        }
      },
      // 备用通道选中状态
      configedSelected(data) {
        console.log('this.bizChannelList', this.bizChannelList)
        console.log('data.channelData', data.channelData.segmentList)
        const checked = data.channelData.checked
        if (checked) {
          const cannotNext = data.channelData.segmentList.some((i, index) => {
            console.log('this.bizChannelList[0]', this.bizChannelList[0])
            return (
              i.status === 'MAIN' &&
              !this.bizChannelList[0].some(j => j.channelId === i.channelId) &&
              !(
                this.bizChannelList[1] &&
                this.bizChannelList[1].some(j => j.channelId === i.channelId)
              )
            )
          })
          if (cannotNext) {
            data.channelData.checked = false
            this.$message.error(this.$t('BACKUP_OCCUPIED'))
            return
          }
          // 选中状态保存通道和链路信息
          this.formData.selectedType = 'configed'
          data.channelData.checked = checked
          if (this.formData.channelData) {
            this.formData.channelData.push(data.channelData)
          } else {
            this.formData.channelData = [data.channelData]
          }
          this.formData.routeData = { ...data.routeData }
          // 获取割接信息
          if (!data.channelData.cutoverList) this.getCutoverList(data.channelData)
        } else {
          if (!this.formData.channelData) return
          // 非选中状态删除已保存通道和链路信息
          this.formData.channelData = this.formData.channelData.filter(
            i => i.backId !== data.channelData.backId
          )
          if (this.formData.channelData.length === 0) {
            this.formData.selectedType = ''
            this.formData.routeData = null
          }
        }
      },
      // 获取割接信息
      async getCutoverList(data) {
        const res = await bizOpenApi.cutoverList({
          firstChannel: data.segmentList
        })
        data.cutoverList = res.firstCutover || []
      },
      // 切换tab重置选中项
      resetSelected() {
        console.log('this.formData.channelData', this.formData.channelData)
        this.formData.routeData &&
          this.formData.channelData.forEach(i => {
            i.checked = false
          })
        this.backChannelList.forEach(i => {
          i.channelList.forEach(j => {
            j.checked = false
          })
        })
        this.formData.routeData = null
        this.formData.channelData = []
      },
      // 重新推荐
      reLinkRecommend() {
        this.formData.routeData = null
        this.formData.channelData = []
        if (this.formatData.selectedType === 'configed') {
          this.getBackDetail()
        } else {
          this.$refs.newRecommend && this.$refs.newRecommend.getRouteList('restore')
        }
        this.step = 1
      },
      close(load) {
        if (this.step === 2 && this.isOtdrTesting && load !== true) {
          this.$confirm(this.$t('CONFIRM_CANCLE_OPEN'), {
            type: 'warning',
            confirmButtonText: this.$t('OK_YES'),
            cancelButtonText: this.$t('OK_NO')
          })
            .then(() => {
              this.showTabs = false
              this.step = 1
              this.$emit('close', load)
            })
            .catch(() => {})
          return
        } else {
          this.showTabs = false
          this.$emit('close', load)
        }
      },
      // otdr测试状态改变
      taskChange(data) {
        this.isOtdrTesting = data
        this.$store.commit('setIsOtdrTesting', data)
      },
      // 获取区域/站点/机房
      getRegionName(stationId) {
        const stationData = this.baseRegionList.find(i => i.regionId === stationId)
        return stationData ? stationData.regionName : ''
      }
    }
  }
</script>

<style scoped>
  .tab-overflow {
    max-height: 300px;
    overflow-y: auto;
  }
</style>
